/* CsJni - .NET / Java Bridge
 * 
 * Copyright 2010 Robert E. Burke Licensed under the Apache License, Version 
 * 2.0 (the "License"); you may not use this file except in compliance with 
 * the License. You may obtain a copy of the License at 
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable 
 * law or agreed to in writing, software distributed under the License is 
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
 * KIND, either express or implied. See the License for the specific language 
 * governing permissions and limitations under the License. 
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace CsJni
{
    [Serializable]
    public class JniException : Exception, ISerializable
    {
        public JniException()
        {
        }

        public JniException(string message) 
            : base(message)
        {
        }

        public JniException(string message, Exception inner)
            : base(message, inner)
        {
        }

        protected JniException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }

        public static void CheckErrorCode(JniEnvironment environment, int code)
        {
            if (code == (int)JniErrorCode.Ok)
            {
                return;
            }
            if (environment == null)
            {
                throw new JniException("TODO");
            }
            // Some error codes may be accompanied with Java Exceptions
            JniThrowable.CheckException(environment);
            HandleBadErrorCode(code);
        }

        internal static void CheckVMErrorCode(int code)
        {
            if (code == (int)JniErrorCode.Ok)
            {
                return;
            }
            HandleBadErrorCode(code);
        }

        private static void HandleBadErrorCode(int code)
        {
            string meaning = JniErrorCodeMeaningAttribute.GetMeaning(code);
            string format = JniResourceManager.Instance.GetString("jniErrorCodeFormat");
            string message = String.Format(CultureInfo.InvariantCulture, format,
                code, meaning);
            throw new JniException(message);
        }

        #region ISerializable Members

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
        }

        #endregion
    }
}
